package com.redoor.app.stake.basicdata.service.impl;

import com.redoor.app.stake.basicdata.commons.BasicDataStatus;
import com.redoor.app.stake.basicdata.dao.BaseRegistrationMapper;
import com.redoor.app.stake.basicdata.model.BaseProp;
import com.redoor.app.stake.basicdata.model.BaseRegistration;
import com.redoor.app.stake.basicdata.model.BaseRegistrationApply;
import com.redoor.app.stake.basicdata.model.BussinessTypeEnum;
import com.redoor.app.stake.basicdata.model.constants.BasePropConstants;
import com.redoor.app.stake.basicdata.model.controllerModel.BasePropCriteria;
import com.redoor.app.stake.basicdata.model.controllerModel.BaseRegistrationApplyCriteria;
import com.redoor.app.stake.basicdata.model.controllerModel.BaseRegistrationCriteria;
import com.redoor.app.stake.basicdata.model.serviceModel.BaseRegistrationServiceBean;
import com.redoor.app.stake.basicdata.mq.sendService.impl.SendMQServiceImpl;
import com.redoor.app.stake.basicdata.service.*;
import com.redoor.app.stake.common.utils.TcuRegSvr;
import com.redoor.app.stake.common.utils.UUIDTool;
import com.redoornetwork.framework.mybatis.service.AbstractService;
import com.yotouch.app.stake.StakeConsts;
import com.yotouch.app.stake.model.Registration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wangjunlei on 2018-03-09 10:22:50.
 */
@Service
@Transactional
public class BaseRegistrationServiceImpl extends AbstractService<BaseRegistration, String> implements BaseRegistrationService {

    private Logger logger = LoggerFactory.getLogger(BaseRegistrationServiceImpl.class);

    @Autowired
    private BaseRegistrationMapper baseRegistrationMapper;

    @Autowired
    private BaseRegistrationApplyService baseRegistrationApplyService;

    @Autowired
    private SendMQServiceImpl mqService;

    @Autowired
    private BasePropService basePropService;

    @Autowired
    private BaseRegistrationRedisService baseRegistrationRedisService;

    @Autowired
    private SyncOrganizationService organizationService;

    @Override
    public int accept(int acceptedAmount,String registrationUuid,String reviewSuggestion) {

        BaseRegistrationApplyCriteria registrationApplyCriteria = new BaseRegistrationApplyCriteria();
        registrationApplyCriteria.setUuid(registrationUuid);
        List<BaseRegistrationApply> baseRegistrationApplies = baseRegistrationApplyService.queryRegistrationApply(registrationApplyCriteria);
        BaseRegistrationApply baseRegistrationApply = (baseRegistrationApplies!=null && baseRegistrationApplies.size()>0)?baseRegistrationApplies.get(0):null;

        /*注册码申请数据不存在,返回30001(目标工单不存在)*/
        if(null == baseRegistrationApply){
            return Integer.parseInt(BasicDataStatus.TARGET_WORKORDER_NOT_EXIST.getCode());
        }

        baseRegistrationApply.setAcceptedamount(acceptedAmount);

        try{
            List<BaseRegistration> baseRegistrationList = new ArrayList<BaseRegistration>();
            String number = "";
            for (int i=1;i<=acceptedAmount;i++){
                if (basePropService.isLocal()){
                    //生成注册码
                    number = System.currentTimeMillis() +"";
                }else {
                    number = genRegCode();
                }

                BaseRegistration baseRegistration = new BaseRegistration();
                baseRegistration.setUuid(UUIDTool.getUUID());
                baseRegistration.setNumber(number);
                baseRegistration.setId(Integer.toString(i));
                baseRegistration.setRegistrationapplyuuid(baseRegistrationApply.getUuid());
                baseRegistration.setStatus(StakeConsts.REGISTRACTION_STATUS_NOT_REGIST);
                /*****begin Description:添加 注册码申请表的组织机构信息到注册码表中  author:zhangMumu  2018/4/19 0019 14:27*****/
                baseRegistration.setProvincecode(organizationService.getProvinceOrgNoByAnOrgNo(baseRegistrationApply.getProrgcode()));
                baseRegistration.setCitycode(organizationService.getCityOrgNoByAnOrgNo(baseRegistrationApply.getProrgcode()));
                /*****end Description:添加 注册码申请表的组织机构信息到注册码表中  author:zhangMumu  2018/4/19 0019 14:27*****/
                baseRegistration.setCreatoruuid(baseRegistrationApply.getCreatoruuid());
                baseRegistration.setCreatedat(new Date());
                baseRegistrationList.add(baseRegistration); //将生成的数据放到集合中，批量insert
            }

            int count = baseRegistrationMapper.insertBatch(baseRegistrationList);

            // 修改注册码申请状态
            baseRegistrationApply.setReviewsuggestion(reviewSuggestion);
            baseRegistrationApply.setUpdatedat(new Date());
            baseRegistrationApply.setStatus(Integer.parseInt(BasicDataStatus.WORKORDER_STATUS_FINISH.getCode()));
            baseRegistrationApplyService.updateBySelective(baseRegistrationApply);

            /*****begin Description:增加判断是否是本地运行  author:zhangMumu edit 2018/4/14 0014 16:49*****/
            /*判断是否是本地运行,不是本地则发送mq.[该值来自于base_prop.isLocal字段]*/
            if(!basePropService.isLocal()){
                mqService.sendMessage("REGISTRATION_APPLY","APPLY",baseRegistrationApply.getUuid(), BussinessTypeEnum.MQ_BUSINESS_TYPE.REGISTRACTION);
            }
            /*****end Description:增加判断是否是本地运行  author:zhangMumu edit 2018/4/14 0014 16:49*****/

        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
        }

        return 1;
    }

    @Override
    public int reject(String registrationUuid, String reviewSuggestion) {
        BaseRegistrationApplyCriteria registrationApplyCriteria = new BaseRegistrationApplyCriteria();
        registrationApplyCriteria.setUuid(registrationUuid);
        List<BaseRegistrationApply> baseRegistrationApplies = baseRegistrationApplyService.queryRegistrationApply(registrationApplyCriteria);
        BaseRegistrationApply baseRegistrationApply = (baseRegistrationApplies!=null && baseRegistrationApplies.size()>0)?baseRegistrationApplies.get(0):null;
        if (baseRegistrationApply==null){
            return 1002;// 没有找到该注册码申请单
        }

        Integer applyStatus = baseRegistrationApply.getStatus();
        if (1000 != applyStatus && applyStatus != Integer.parseInt(BasicDataStatus.WORKORDER_STATUS_APPLYING.getCode())){
            return 1003;//该工单已经审核过了
        }

        // 修改注册码申请状态
        baseRegistrationApply.setReviewsuggestion(reviewSuggestion);
        baseRegistrationApply.setUpdatedat(new Date());
        baseRegistrationApply.setStatus(Integer.parseInt(BasicDataStatus.WORKORDER_STATUS_REJECT.getCode()));
        baseRegistrationApplyService.updateBySelective(baseRegistrationApply);

        mqService.sendMessage("REGISTRATION_APPLY","APPLY",baseRegistrationApply.getUuid(), BussinessTypeEnum.MQ_BUSINESS_TYPE.REGISTRACTION);

        return 1;
    }

    private String genRegCode(){

        //从缓存获取registrationIndex
        Double index = basePropService.getRegisterIndex();

        String registrationPeriod = basePropService.getProp(BasePropConstants.registrationPeriods);
        if (StringUtils.isEmpty(registrationPeriod)){
            registrationPeriod = "17-12-31";
        }

        String softPeriodStart = basePropService.getProp(BasePropConstants.softPeriodStart);
        if (StringUtils.isEmpty(softPeriodStart)) {
            softPeriodStart = "17-06-01";
        }

        String softPeriodEnd = basePropService.getProp(BasePropConstants.softPeriodEnd);
        if (StringUtils.isEmpty(softPeriodEnd)) {
            softPeriodEnd = "99-12-31";
        }

        String serailType = basePropService.getProp(BasePropConstants.softType);
        if (StringUtils.isEmpty(serailType)) {
            //获取注册码类型，1 - 试用，2 - 正式
            serailType =  "1" ;
        }
        int type = Integer.parseInt(serailType) ;
        String code = TcuRegSvr.generateSerial(type, index.intValue(), registrationPeriod, softPeriodStart, softPeriodEnd);

        //todo 更新index到数据库后续考虑使用定时批量更新
        BasePropCriteria propConstants = new BasePropCriteria();
        propConstants.setName(BasePropConstants.registrationIndex);

        BaseProp prop = basePropService.getProp(propConstants);
        prop.setValue(index.intValue()+"");
        basePropService.updateBySelective(prop);

        return code;
    }

    /**
     * 生产环境调用网络注册码生成方式
     *
     * @param fingerprint
     * @param regCode
     * @param stakeNo
     * @return
     */
    public String genAuthCode(String fingerprint, String regCode, String stakeNo) {

        //非生产环境生成随机数
        if (basePropService.isLocal()){
            return String.valueOf(System.currentTimeMillis());
        }

        String softPeriodStart = basePropService.getProp(BasePropConstants.softPeriodStart);
        if (StringUtils.isEmpty(softPeriodStart)){
            softPeriodStart = "17-12-31";
        }

        String softPeriodEnd = basePropService.getProp(BasePropConstants.softPeriodEnd);
        if (StringUtils.isEmpty(softPeriodEnd)){
            softPeriodStart = "99-12-31";
        }

        String softPeriod = softPeriodStart + "-" + softPeriodEnd ;
        return TcuRegSvr.generateAuthCode(fingerprint, stakeNo, regCode, softPeriod) ;
    }

    @Override
    public List<BaseRegistrationServiceBean> qryRegistrationList(BaseRegistrationCriteria criteria) {
        return this.baseRegistrationMapper.qryRegistrationList(criteria);
    }

    @Override
    public int qryRegistrationTotal(BaseRegistrationCriteria criteria) {
        return this.baseRegistrationMapper.qryRegistrationTotal(criteria);
    }

    @Override
    public List<BaseRegistration> queryRegistration(BaseRegistrationCriteria criteria) {
        return null;
    }

    @Override
    public BaseRegistration getRegistrationByNumber(String number) {
        if (StringUtils.isEmpty(number)){
            logger.warn("BaseRegistrationServiceImpl-->getRegistrationByNumber : 查询参数不能为空!");
            return null;
        }

        BaseRegistration baseRegistration = null;
        String uuid = baseRegistrationRedisService.getUuidByNumber(number);
        if (!StringUtils.isEmpty(uuid)){
            baseRegistration = baseRegistrationRedisService.getRegistration(uuid);
        }

        if (baseRegistration == null) {
            BaseRegistrationCriteria criteria = new BaseRegistrationCriteria();
            criteria.setNumber(number);
            List<BaseRegistration> baseRegistrationList = baseRegistrationMapper.queryRegistration(criteria);
            baseRegistration = (baseRegistrationList != null && baseRegistrationList.size() > 0) ? baseRegistrationList.get(0) : null;
            if (baseRegistration!=null){
                baseRegistrationRedisService.modifyInfo(baseRegistration);
            }
        }
        return baseRegistration;
    }

    @Override
    public String getRegistrationUuidByNumber(String number) {
        if (StringUtils.isEmpty(number)){
            logger.warn("BaseRegistrationServiceImpl-->getRegistrationUuidByNumber : 查询参数不能为空!");
            return null;
        }

        String uuid = baseRegistrationRedisService.getUuidByNumber(number);// 从缓存中查找

        if (StringUtils.isEmpty(uuid)){
            BaseRegistrationCriteria criteria = new BaseRegistrationCriteria();
            criteria.setNumber(number);
            List<BaseRegistration> baseRegistrationList = baseRegistrationMapper.queryRegistration(criteria);
            BaseRegistration baseRegistration = (baseRegistrationList != null && baseRegistrationList.size() > 0) ? baseRegistrationList.get(0) : null;
            if (baseRegistration!=null){
                uuid = baseRegistration.getUuid();
                baseRegistrationRedisService.modifyInfo(baseRegistration);// 添加到缓存
            }
        }
        return uuid;
    }

    @Override
    public BaseRegistration getRegistrationByUuid(String uuid) {
        if (StringUtils.isEmpty(uuid)){
            logger.info("BaseRegistrationServiceImpl-->getRegistrationByUuid : 查询参数不能为空!");
            return null;
        }

        BaseRegistration baseRegistration = baseRegistrationRedisService.getRegistration(uuid); // 根据主键从缓存中查找数据

        if (baseRegistration==null) {
            BaseRegistrationCriteria criteria = new BaseRegistrationCriteria();
            criteria.setUuid(uuid);
            List<BaseRegistration> baseRegistrationList = baseRegistrationMapper.queryRegistration(criteria);
            baseRegistration = (baseRegistrationList != null && baseRegistrationList.size() > 0) ? baseRegistrationList.get(0) : null;

            if (baseRegistration!=null){
                baseRegistrationRedisService.modifyInfo(baseRegistration); // 将数据缓存到redis
            }
        }
        return baseRegistration;
    }

    @Override
    public List<Registration> queryHsfRegistration(String registrationApplyUuid) {

        List<Registration> registrations = baseRegistrationMapper.queryHsfRegistration(registrationApplyUuid);
        return registrations;
    }

    @Override
    public int insertBatch(List<BaseRegistration> list) {
        if(CollectionUtils.isEmpty(list)){
            return -1;
        }
        return baseRegistrationMapper.insertBatch(list);
    }
}
